<!--
 * @Author: ZCL
 * @Date: 2020-05-20 10:55:22
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-07-24 10:54:42
-->
<template>
  <!-- 资产领用 -->
  <div class="assetReceive">
    <van-cell
      title="请选择仓库:"
      is-link
      :value="currentStore.name"
      @click="showAction = true"
    />
    <van-action-sheet
      v-model="showAction"
      :actions="stores"
      cancel-text="取消"
      @select="handleGetCateGory"
      @cancel="showAction = false"
    />
    <van-tree-select
      :items="items"
      :main-active-index.sync="active"
      @click-nav="handleGetReceive"
    >
      <template #content>
        <template v-if="goods.length">
          <div v-for="(good,index) in goods" :key="'a' + index">
            <div class="title" >{{ good.category_name }}</div>
            <div class="box" v-for="(item, index) in good.list" :key="'b' + index">
              <div class="left" @click="goDetail(item.re_a_id)">
                <van-image
                  width="100px"
                  height="100px"
                  :src="item.image_url"
                />
              </div>
              <div :class="$type === $const.COMMON_TYPES.CONSUMABLE?'right': 'right2'">
                <div class="right-top" @click="goDetail(item.re_a_id)">
                  <p class="text">{{ item.c_name }}</p>
                  <p>型号：{{ item.c_specs }} </p>
                  <p>编码：{{ item.c_code }} </p>
                  <p v-if="$type === $const.COMMON_TYPES.CONSUMABLE">库存：{{ item.c_stock }} </p>
                </div>
                <div class="right-bottom">
                  <van-button
                    class="mt-2"
                    type="info"
                    size="small"
                    round
                    :disabled="!item.c_stock"
                    @click="handleCart(cartTypes.ADD_GOOD, item)"
                    v-show="!cartIds.includes(item.re_a_id)"
                  >加入领用单</van-button>
                  <van-button
                    class="mt-2"
                    type="info"
                    size="small"
                    round
                    color="#E1E1E1"
                    @click="handleCart(cartTypes.MINUS_GOOD, item)"
                    v-show="cartIds.includes(item.re_a_id)"
                  >已加入领用单</van-button>
                </div>
              </div>
            </div>
            <div class="des" v-if="!good.list.length" :key="good.id">该分类暂无内容 :)</div>
          </div>
          <div class="des">- 我是有底线的 -</div>
        </template>
        <van-empty image="search" description="该分类暂无内容 :)" v-else/>
      </template>
    </van-tree-select>
    <div class="icon" @click="goAddAsset">
      <van-icon :name="require('@/assets/icon/asset/add.png')" :badge="cartIds.length" size="65px" />
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex';
import { types as cartTypes } from '@/store/modules/cart';
import { categoryName } from '@/utils';
import titleMixins from '@/mixins/title';

export default {
  name: 'AssetReceive',
  mixins: [titleMixins],
  computed: {
    ...mapGetters(['cartIds', 'dept_id'])
  },
  data () {
    return {
      showAction: false, // 显示仓库选项
      stores: [], // 仓库列表
      currentStore: {}, // 当前选中的仓库
      goods: [], // 耗材/资产列表
      items: [], // 左侧分类列表
      active: 0, // 当前激活的左侧分类选项
      cartTypes
    };
  },
  methods: {
    ...mapMutations('cart', [ ..._.keys(cartTypes) ]),
    // 处理购物车逻辑
    handleCart (type, payload) {
      this[type](payload);
    },
    // 前往详情
    goDetail (id) {
      let query = {
        id
      };
      if (this.$type === this.$const.COMMON_TYPES.ASSET) {
        query.type = this.$const.COMMON_TYPES.ASSET;
        this.$router.push({
          name: 'asset-detail',
          query
        });
      } else if (this.$type === this.$const.COMMON_TYPES.CONSUMABLE) {
        query.type = this.$const.COMMON_TYPES.CONSUMABLE;
        this.$router.push({
          name: 'consumables-detail',
          query
        });
      }
    },
    // 前往资产领用单
    goAddAsset () {
      if (!this.cartIds.length) {
        // this.$notify({
        //   type: 'warning',
        //   message: `请选择需要领取的内容 :)`
        // });
        this.$toast('请选择需要领取的内容');
        return;
      }
      const { COMMON_TYPES } = this.$const;
      const titles = {
        [COMMON_TYPES.ASSET]: '资产领用单',
        [COMMON_TYPES.CONSUMABLE]: '耗材领用单'
      };
      this.$router.push({
        name: 'asset-receive-sheet',
        query: {
          title: titles[this.$type],
          type: this.$type,
          wh_id: this.currentStore.wh_id
        }
      });
    },
    // 获取所在部门拥有的仓库列表
    handleGetStores () {
      const params = {
        dept_ids: this.dept_id
      };
      const { COMMON_TYPES } = this.$const;
      if (this.$type === COMMON_TYPES.ASSET) {
        this.$api.getAssetHaveWarehouse(params).then(res => {
          if (res.code === 0) {
            const stores = _.get(res, 'result.data') || [];
            this.stores = stores.map(item => ({ ...item, name: item.wh_name }));
            if (this.stores.length) {
              this.handleGetCateGory(this.stores[0]);
              this.currentStore = this.stores[0];
            } else {
              // this.$notify({
              //   type: 'primary',
              //   message: '暂无仓库权限,请联系管理员:)'
              // });
              this.$toast('暂无仓库权限,请联系管理员');
            }
          }
        });
      } else if (this.$type === COMMON_TYPES.CONSUMABLE) {
        this.$api.getConsumableHaveWarehouse(params).then(res => {
          if (res.code === 0) {
            const stores = _.get(res, 'result.data') || [];
            this.stores = stores.map(item => ({ ...item, name: item.wh_name }));
            if (this.stores.length) {
              this.handleGetCateGory(this.stores[0]);
              this.currentStore = this.stores[0];
            } else {
              // this.$notify({
              //   type: 'primary',
              //   message: '暂无仓库权限,请联系管理员:)'
              // });
              this.$toast('暂无仓库权限,请联系管理员');
            }
          }
        });
      }
    },
    // 获取仓库下耗材分类列表 / 切换仓库
    handleGetCateGory (store) {
      const { COMMON_TYPES } = this.$const;
      const params = {
        // 1. 耗材 2.资产
        category_type: COMMON_TYPES.ASSET === this.$type ? 2 : 1,
        wh_id: store.wh_id
      };
      // 关闭仓库选项及记录弹窗
      this.showAction = false;
      if (this.currentStore && this.currentStore.wh_id === store.wh_id) return;

      this.currentStore = store;

      this.$api.getCateGoryIndex(params).then(res => {
        if (res.code === 0) {
          const items = res.result || [];
          // 初始化获取数据标记
          items.forEach(item => {
            item.fetch = false;
          });
          this.items = categoryName(items);
          if (!this.items.length) {
            this.$toast('该仓库下暂无内容');
            this.goods = [];
          } else {
            this.handleGetReceive();
          }
        }
      });
    },
    // 获取分类下课领取的耗材/资产
    handleGetReceive () {
      const activeItems = _.get(this.items, `${this.active}`);
      const c_cid = _.get(activeItems, 'id');
      const wh_id = _.get(this.currentStore, 'wh_id');
      if (_.isUndefined(c_cid) || _.isUndefined(wh_id)) {
        // this.$notify({
        //   type: 'warning',
        //   message: '分类数据获取异常 :)'
        // });
        this.$toast('分类数据获取异常');
        return;
      }

      // 防止重新请求数据获取过数据的,读取现有数据即可
      if (activeItems.fetch) {
        this.goods = activeItems.cate;
        return;
      }

      const params = {
        wh_id,
        c_cid
      };
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0

      });
      if (this.$type === this.$const.COMMON_TYPES.ASSET) {
        this.$api.getAssetReceiveIndex(params).then(res => {
          activeItems.fetch = true;
          activeItems.cate = res.result;
          this.goods = activeItems.cate;
          this.goods.forEach(item => {
            item.list = item.list.map(item2 => ({
              ...item2,
              c_name: item2.f_name,
              c_code: item2.f_code,
              c_specs: item2.f_specs,
              c_stock: 1
            }));
          });
        }).finally(() => {
          this.$toast.clear();
        });
      } else if (this.$type === this.$const.COMMON_TYPES.CONSUMABLE) {
        this.$api.getConsumableReceiveIndex(params).then(res => {
          activeItems.fetch = true;
          activeItems.cate = res.result;
          this.goods = activeItems.cate;
        }).finally(() => {
          this.$toast.clear();
        });
      }
    }
  },
  created () {
    this.handleGetStores(); // 获取所在部门拥有的仓库列表
    this.handleCart(cartTypes.SET_TYPE, this.$type);
  }
};
</script>

<style lang="scss" scoped>
$cell-height: 44;

.assetReceive {
  ::v-deep {
    .van-cell {
      height: $cell-height + px;
      box-sizing: border-box;
      margin-bottom: 10px;
    }
    .van-cell__title, .van-cell__value {
      color: #2D2D2D;
      font-size: 14px;
    }
  }
  .box {
    display: flex;
    padding: 10px 0;
    margin: 0 15px;
    border-bottom: 1px solid #F5F5F5;
    .left {
      margin-right: 15px;
    }
    .right {
      font-size: 12px;
      color: #ABABAB;
      line-height: 19px;
      .text {
        color: #343434;
        font-size: 14px;
      }
    }
    .right2 {
      font-size: 12px;
      color: #ABABAB;
      line-height: 24px;
      .text {
        color: #343434;
        font-size: 14px;
      }
    }
    ::v-deep.van-button--small {
      height: 22px;
    }
  }
  .title {
    padding: 14px 0 10px;
    margin: 0 15px;
    color: #101010;
    font-size: 14px;
    border-bottom: 1px solid #F5F5F5;
  }
  ::v-deep {
    .van-tree-select__nav {
      background-color: #eef2f4;
      width: 90px;
      flex: initial;
      height: calc(100vh - #{$cell-height + 10}px);
    }
    .van-sidebar-item {
      background-color: #eef2f4;
      padding: 10px;
    }
    .van-sidebar-item--select {
      background-color: #fff;
      &:active, &:before {
        background-color: #fff;
      }
      &:active {
        padding: 10px;
      }
      .van-sidebar-item__text {
        color: #1890FE;
        font-weight: bold;
      }
    }
    .van-tree-select__content {
      height: calc(100vh - #{$cell-height + 10}px);
    }
    .van-sidebar-item__text {
      font-size: 14px;
      color: #6C6C6C;
    }
  }
  .icon {
    position: fixed;
    bottom: 10px;
    right: 10px;
  }
  .van-info {
    right: 12px;
    top: 11px;
  }
}
</style>
